<template>
  <div class="recive-document" v-loading="loading" element-loading-background="rgba(255, 255, 255,1)">
    <div class="title">
      收文处理笺
    </div>
    <table class="table-wrapper" border="1px" cellspacing="0" cellpadding="0">
      <tr height="40">
        <td width="12%" align="center">来文单位</td>
        <td width="35%">
          <span>{{ pager.department }}</span></td>
        <td width="12%" align="center">收文日期</td>
        <td width="35%">
          <span>{{ parseTime(pager.issued_date,'{y}-{m}-{d}') || '' }}</span>
        </td>
      </tr>
      <tr height="40">
        <td align="center">文件标题</td>
        <td colspan="4">
          <span>{{ pager.title}}</span>
        </td>
      </tr>
      <tr height="40">
        <td width="10%" align="center">来文字号</td>
        <td width="35%">
          <span>{{ pager.issued_number }}</span>
        </td>
        <td width="12%" align="center">缓急程度</td>
        <td width="35%">
          <span>{{ pager.emergency_level }}</span>
        </td>
      </tr>
      <tr height="40">
          <td width="10%" align="center">上报类型</td>
          <td width="35%" class="input-content">
            <span>{{ pager.classify_name}}</span>
          </td>
          <td width="12%" align="center">任务类别</td>
          <td width="35%" class="input-content">
            <span>{{ pager.data_type}}</span>
          </td>
        </tr>
      <tr class="situation">
        <td width="30" align="center">拟办意见</td>
        <td colspan="4" class="content">
          <el-input type="textarea" :rows="4" v-model="suggestion"></el-input>
        </td>
      </tr>
      <!-- <tr class="situation">
              <td width="30" align="center">领导批示</td>
              <td colspan="4" class="content">
                <div class="inform" v-for="(item,index) in situation">
                  <div>{{ item.fullMessage }}</div>
                  <div class="info">
                    <div class="info-name">{{ item.userId }}</div>
                    <div>{{ item.date }}</div>
                  </div>
                </div>
              </td>
            </tr> -->
      <!-- <tr class="situation" v-for="(val, key, index) in pointData" :key="index">
        <td width="30" align="center">{{ key}}</td>
        <td colspan="4" class="content">
          <div class="inform" v-for="(p,i) in pointData[key]" :key="i">
            <div>{{ p.message }}</div>
            <div class="info">
              <div class="info-name">{{ p.userId }}</div>
              <div>{{ p.time | formatTime}}</div>
            </div>
          </div>
        </td>
      </tr> -->
    </table>
    <el-divider></el-divider>
    <el-row type="flex" justify="center">
      <!-- <el-button type="primary" size="small" @click="handReceive">签收</el-button> -->
      <el-button type="primary" size="small" @click="showSelectUserDialog(false)">签收</el-button>
      <!-- <el-button type="primary" size="small" @click="showSelectUserDialog(true)">委托</el-button> 
      <el-button type="primary" size="small" @click="showDialogProcess">流程监控</el-button>-->
    </el-row>
    <!-- 流程监控 -->
    <process-monitor ref="process" :fromTask="true" :showPager="false" :activities="activities" :processStatics="processStatics"></process-monitor>
    <!-- 委托人 -->
    <el-dialog title="选择审批人" :visible.sync="dialogSelectUser" width="80%">
      <user-manager ref="userManager" :userOuter="false" :onSelectUsers="handReceiveComplete" />
    </el-dialog>
  </div>
</template>

<script>
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  import {
    mapGetters
  } from "vuex";
  import {
    getInfo
  } from '@/api/user.js'
  import {
    getPaperClassify,
    createDocument,
    getPagerById
  } from "@/api/document.js";
  import {
    updateTaskPart
  } from '@/api/work.js'
  import {
    getProcess,
    getProcessPointNames,
    startProcess,
    completeTasks,
    getCommentPro,
    getProcessMinitor,
    postEntrustToOther,
    claimTask,
    claimAndCompleteTask,
    getTaskProcessInfo1
  } from "@/api/workflow.js";
  import {
    parseTime
  } from "@/utils/index";
  
  import axios from 'axios'
  import Cookies from 'js-cookie'

  export default {
    name: "HandlePager",
    components: {
      Treeselect,
      'userManager': () => import('@/views/markSys/taskCenter/components/userManager.vue'),
      'process-monitor': () => import('../components/ProcessMinitor/index.vue')
    },
    props: {
      pager: {
        type: Object
      }
    },
    data() {
      return {
        //   pager: {},
        dialogSelectUser: false,
        consignor: '', // 委托用户
        circulationUser: '', // 所有用户列表
        activities: [],
        loading: false,
        dialogProcessVisible: false,
        isEntrust: false,
        queryData: null,
        pointNameList: [], // 流程节点名称
        pointData: [],
        processStatics: {
            curCount: 0,
            doneCount: 0,
            willCount: 0
          }, // 流程监控节点统计
        suggestion: '', // 拟办意见
      };
    },
    computed: {
      inpNum() {
        return this.document.printAmount
      },
      ...mapGetters([
        'id',
        'name'
      ]),
    },
    created() {
      this.queryData = this.$route.params
      this.requestCirculationUser()
      // this.requestPager();
      // this.requestProcessPointNames()
      // this.requestCommenthi()
    },
    watch: {

    },
    methods: {
      parseTime,
      // 处理签收
      handReceive() {
        const param = {
          userId: this.id,
          suggestion: this.suggestion
        }
        claimTask(this.queryData.id, param).then(
          res => {
            if (res && res.data && res.data.code == '200') {
              this.$notify({
                title: '提示',
                message: '任务签收成功',
                type: 'success'
              });
              this.$router.push({
                name: 'Index'
              })
            }
          }
        )
      },
      // 处理签收并完成
      handReceiveComplete(users) {
        if(!users.length){
          this.$message.warning('请选择处理人')
          return
        }
        claimTask(this.queryData.id, {
          userId: this.id,
          suggestion: this.suggestion,
          dealReason: this.suggestion,
          dealType: '0',
          dealUserId: this.id,
          dealUserName: this.name,
          dealUnitId: "0"
        }).then(
          res => {
            if (res && res.data.message === "签收任务成功") {
              this.dialogSelectUser = false
              this.createTask()
            }
          }
        )
      },
      // 显示选择委托人对话框
      showSelectUserDialog(flag = false) {
        this.dialogSelectUser = true
        this.isEntrust = flag
      },
      // 处理委托
      handSelectConsignor() {
        const users = this.$refs.userManager.sureUsersList
        if (!users.length) {
          this.$message.warning('请选择委托人')
          return
        }
        if (this.isEntrust) {
          postEntrustToOther(this.queryData.targetId, users[0].id).then(
            res => {
              if (res && res.data.message === "转发任务成功") {
                this.dialogSelectUser = false
                this.$notify({
                  title: '成功',
                  message: '转发任务成功',
                  type: 'success'
                });
              }
            }
          )
        } else {
          this.handReceiveComplete()
        }
      },
      // 提交任务信息
      createTask() {
        const {
          title,
          body,
          end_time,
          classify,
          data_type,
          emergency_level,
          parent,
          id,
          issued_number,
          issued_date
        } = this.pager
        const param = {
          body: body,
          title: title,
          is_approval: 'True',
          end_time: end_time,
          emergency_level: emergency_level,
          data_type: data_type,
          classify: classify,
          issued_number: issued_number,
          issued_superior: id,
          issued_date: issued_date
        }
        // const users = this.$refs.userManager.sureUsersList
        var form = new FormData()
        for (const key of Object.keys(param)) {
          form.append(key, param[key])
        }
        // if (users) {
        //   for (let i = 0; i < users.length; i++) {
        //     form.append('user', users[i].id)
        //   }
        // }
        var config = {
          headers: {
            'Content-Type': 'multipart/form-data',
            'X-CSRFToken': Cookies.get('csrftoken')
          }
        }
        axios.post(`/api/Work/Task/`,
          form, config).then((res) => {
          if (res.data) {
            this.publishTask(res.data)
          }
        })
      },
      // 发布任务
      publishTask(pager){
        const users = this.$refs.userManager.sureUsersList
        const formatUsers= users.map(e => e.id.toString())
        const {
          title,
          end_time,
          classify,
          classify_name,
          data_type,
          emergency_level,
          user,
          id
        } = pager
        const param = {
              businessKey: id,
              bussName:title,
              bussType:"SP",
              targetUnitId:"",
              startUserId: this.id,
              startUserName: this.name,
              emergency: emergency_level,
              classify_name: classify_name,
              end_time: end_time,
              userList: formatUsers,
              circulation_user: this.circulationUser
            }
            // "userList": user
        startProcess('SPNB001', param).then(res =>{
          if(res && res.data){ 
            updateTaskPart(id, {is_publish: 'True', user: formatUsers}).then(
              res =>{
                if(res && res.data){
                  this.$notify({
                    title: '提示',
                    message: '转内部流程成功',
                    type: 'success'
                  });
                  this.$router.push({
                    name: 'Index'
                  })
                }
              }
            )
          }
        })
      },
    // 显示流程监控页面
    showDialogProcess() {
      this.requestProcessMinitor()
      this.$refs.process.dialogProcessVisible = true
    },
    // 获取流程监控数据
    requestProcessMinitor() {
      // let result = []
      // Object.keys(this.pointData).forEach(
      //   key => {
      //     let point = this.pointData[key]
      //     if (point.length) {
      //       point.forEach(
      //         e => {
      //           e.name = key
      //         }
      //       )
      //       result = result.concat(point)
      //     }
      //   }
      // )
      getTaskProcessInfo1(this.pager.id).then(
          res =>{
            const { curCount, doneCount, willCount, data } = res.data && res.data.data || {}
            this.activities = data
            this.processStatics = {
              curCount: curCount,
              doneCount: doneCount,
              willCount: willCount
            }
          })
    },
    // 获取流程节点名称
    requestProcessPointNames() {
      getProcessPointNames(this.queryData.proDefId).then(
        res => {
          res.data.data.shift()
          const list = res.data.data
          let data = []
          list.forEach(
            e => {
              data.push({
                name: Object.values(e)[0]
              })
            }
          )
          this.pointNameList = data
        }
      )
    },
    // 请求用户信息列表
    requestCirculationUser(){
      getInfo(this.id).then(
        res =>{
          if(res && res.data)
          this.circulationUser = res.data.circulation_user
        }
      )
    },
    requestPager() {
      getPagerById(this.queryData.id).then(
        res => {
          this.pager = res.data
        }
      )
    },
    // 获取审批记录
    requestCommenthi() {
      const {
        proInsId,
        proDefId
      } = this.queryData
      getCommentPro(proInsId, proDefId).then(
        res => {
          this.pointData = res.data.data
        }
      )
    }
  }
  }
</script>
<style media="printContent">
  @page {
    size: auto;
    /* auto is the initial value */
    margin: 0mm 15mm 0;
  }

</style>
<style lang="scss">
  .recive-document {
    margin: 0 20px 20px;
    overflow-x: hidden;

    .table-wrapper {
      border-collapse: collapse;
      border: none;
    }

    .table-wrapper td {
      border: 1px solid red;
    }

    .title {
      text-align: center;
      font-size: 25px;
      color: red;
      padding: 15px 0px;
    }

    .table-wrapper {
      width: 100%;
      max-width: 800px;
      font-size: 14px;
      font-weight: bold;
      border-color: #f443367a;
      color: red;
      margin: 0 auto;

      .situation {
        min-height: 80px;
        height: 80px;

        .content {
          margin: 0 10px;
          padding: 10px;

          .inform {
            height: 70px;
            padding: 10px;
            margin: 0 10px;
            border-bottom: 1px solid #ccc;
            color: #000;
            font-weight: normal;

            &-comment {
              width: 60%;
            }

            .info {
              float: right;
              font-size: 12px;
              text-align: center;
              color: #797979;

              &-name {
                padding: 6px;
              }
            }

            &:last-child {
              border: none;
            }
          }
        }
      }

      td {
        span {
          margin-left: 10px;
          color: #000;
          font-weight: normal;
        }
      }

      .radio-group {
        margin-left: 15px;
      }

      .el-input__inner {
        background-color: transparent;
        border: 0;
      }
    }

    .process-info {
      padding-left: 5px;

      .user {
        float: right;
        padding: 3px 0;

        .icon {
          padding-right: 3px;
        }
      }

      .content {
        font-size: 12px;
        color: #999;

        .time {
          display: inline-block;
          padding: 10px 0;
        }
      }
    }

    .el-divider--horizontal {
      margin: 24px auto;
    }

    .el-card__header {
      padding: 10px 20px;
    }

    .el-button+.el-button {
      margin-left: 10px;
    }
  }

</style>
